package com.xiaochong.bitong.api.webWs;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xc.logclient.utils.LogTrace;
import com.xiaochong.bitong.api.config.ExecutorConfig;
import com.xiaochong.bitong.api.constant.ReturnCode;
import com.xiaochong.bitong.api.service.KActionDetailService;
import com.xiaochong.service.common.config.redis.RedisServer;
import com.xiaochong.tir.common.data.hbasepo.TradesToKLine;
import com.xiaochong.tir.common.data.po.OrderResultVo;
import com.xiaochong.tir.common.data.vo.ApiResultVo;
import com.xiaochong.tir.common.data.vo.ApiTradesHistoryVo;
import com.xiaochong.tir.common.data.vo.ApiWebSocketVo;
import com.xiaochong.tir.common.data.vo.app.AppOrderBookVo;
import com.xiaochong.tir.common.data.vo.app.AppSelfSelectCoinPairVo;
import com.xiaochong.tir.common.util.RedisKeyApp;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.websocket.Session;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: appWs
 * @Author: org
 * @CreateDate: 2018/8/9 20:10
 */
@Component("AsyncWsPush")
public class AsyncWsPush {

    public  static final long  WAIT_TIME = 10000;
    @Autowired
    private KActionDetailService kActionDetailService;
    @Autowired
    private RedisServer redisServer;
    /**
     * 历史交易时时刷新、表头数据，k线数据
     * @param session
     * @param exchangeId
     * @param transactionName
     */
    @Async(ExecutorConfig.WS_REQ_ASYNC)
    public void tranes(Session session, int exchangeId, String transactionName) {
        LogTrace.beginTrace("发送消息");
        ApiResultVo resultVo = new ApiResultVo();
        resultVo.setDataStamp(System.currentTimeMillis());
        resultVo.setTradeId(LogTrace.getTrace().getTraceId());
        //String symbol = redisServer.get(RedisKeyApp.APP_WS_K_SESSION_ID+":"+session.getId());

        if (session.isOpen()) {
            LogTrace.infoKvs("ws-tranes-kline-rise-data","sessionId" ,session.getId(),"exchangeId",String.valueOf(exchangeId),"transactionName",transactionName);
            try {
                List<ApiTradesHistoryVo> tradesHistoryVos = kActionDetailService.getTreasMakeDate(exchangeId,transactionName);
                JSONObject jsonObject = kActionDetailService.makeRiseData(exchangeId,transactionName);
                List<TradesToKLine> kLineList = kActionDetailService.makekActionNewData(String.valueOf(exchangeId),transactionName);
                Map<String,Object> result = new HashMap();
                result.put("trades",jsonObject);
                result.put("rise",tradesHistoryVos);
                result.put("kLine",kLineList);
                result.put("type","kline");
                resultVo.setData(result);
                resultVo.setCode(ReturnCode.SUCCESS);
                resultVo.setMessage("成功");
                /*if(StringUtils.isBlank(symbol)){
                    redisServer.set(RedisKeyApp.APP_WS_K_SESSION_ID+":"+session.getId(),transactionName,10L);
                }else{
                    resultVo.setCode(ReturnCode.DATA_NOT_EXIST);
                    resultVo.setMessage("10秒内不能多次请求");
                }*/
            } catch (Exception e) {
                e.printStackTrace();
                resultVo.setCode(ReturnCode.ERROR);
                resultVo.setMessage("系统异常");
                LogTrace.error("ws-tranes-kline-rise-error",e);
            }
            try {
                session.getBasicRemote().sendText(JSON.toJSONString(resultVo));
            } catch (IOException e) {
                e.printStackTrace();
                LogTrace.info("ws-tranes-kline-rise-wsError","websocket","断开连接或异常");
            }
        }
    }

    public void depth(Session session, Integer exchangeId, String transactionName) {
        LogTrace.beginTrace("发送消息");
        ApiResultVo resultVo = new ApiResultVo();
        resultVo.setDataStamp(System.currentTimeMillis());
        resultVo.setTradeId(LogTrace.getTrace().getTraceId());
        //String symbol = redisServer.get(RedisKeyApp.APP_WS_K_SESSION_ID+":"+session.getId());

        if (session.isOpen()) {
            LogTrace.infoKvs("ws-depth-order-data","sessionId" ,session.getId(),"exchangeId",String.valueOf(exchangeId),"transactionName",transactionName);
            try {
                //获取深度
                OrderResultVo depth = kActionDetailService.MakeDepth(exchangeId,transactionName);
              //  Map<String,List<AppOrderBookVo>> order = kActionDetailService.makeOrderBookLast(exchangeId,transactionName);
                //获取委单（买单和买单各15条）
                Map<String,Object> result = new HashMap();
                result.put("depth",depth);
              //  result.put("order",order);
                result.put("type","depth");
                resultVo.setData(result);
                resultVo.setCode(ReturnCode.SUCCESS);
                resultVo.setMessage("成功");
            } catch (Exception e) {
                e.printStackTrace();
                resultVo.setCode(ReturnCode.ERROR);
                resultVo.setMessage("系统异常");
                LogTrace.error("ws-depth-order-data-error",e);
            }
            try {
                session.getBasicRemote().sendText(JSON.toJSONString(resultVo));
            } catch (IOException e) {
                e.printStackTrace();
                LogTrace.info("ws-depth-order-data","websocket","断开连接或异常");
            }
        }
    }

    /**
     * 根据id获取货币数据
     * @param session
     * @param id
     */
    public void currency(Session session, Integer id) {
        LogTrace.beginTrace("发送消息");
        ApiResultVo resultVo = new ApiResultVo();
        resultVo.setDataStamp(System.currentTimeMillis());
        resultVo.setTradeId(LogTrace.getTrace().getTraceId());
        //String symbol = redisServer.get(RedisKeyApp.APP_WS_K_SESSION_ID+":"+session.getId());

        if (session.isOpen()) {
            LogTrace.infoKvs("ws-currency-data","sessionId" ,session.getId(),"currency",String.valueOf(id));
            try {
                //获取货币数据
                AppSelfSelectCoinPairVo currencyData = kActionDetailService.getCurrencyData(id);
                //获取货币数据
                resultVo.setData(currencyData);
                resultVo.setCode(ReturnCode.SUCCESS);
                resultVo.setMessage("成功");
            } catch (Exception e) {
                e.printStackTrace();
                resultVo.setCode(ReturnCode.ERROR);
                resultVo.setMessage("系统异常");
                LogTrace.error("ws-currency-data-error",e);
            }
            try {
                session.getBasicRemote().sendText(JSON.toJSONString(resultVo));
            } catch (IOException e) {
                e.printStackTrace();
                LogTrace.info("ws-currency-data","websocket","断开连接或异常");
            }
        }
    }

    /**
     * 根据发送货币id，获取货币数据
     * @param session
     * @param message
     */
    public void currency(Session session, String message) {
        LogTrace.beginTrace("发送消息");
        ApiResultVo resultVo = new ApiResultVo();
        resultVo.setDataStamp(System.currentTimeMillis());
        resultVo.setTradeId(LogTrace.getTrace().getTraceId());
        //String symbol = redisServer.get(RedisKeyApp.APP_WS_K_SESSION_ID+":"+session.getId());

        if (session.isOpen()) {
            LogTrace.infoKvs("ws-currency-data","sessionId" ,session.getId(),"currency",message);
            try {
                //获取货币数据
                List<AppSelfSelectCoinPairVo> currencyData = kActionDetailService.getCurrencyData(message);
                //获取货币数据
                resultVo.setData(currencyData);
                resultVo.setCode(ReturnCode.SUCCESS);
                resultVo.setMessage("成功");
            } catch (Exception e) {
                e.printStackTrace();
                resultVo.setCode(ReturnCode.ERROR);
                resultVo.setMessage("系统异常");
                LogTrace.error("ws-currency-data-error",e);
            }
            try {
                session.getBasicRemote().sendText(JSON.toJSONString(resultVo));
            } catch (IOException e) {
                e.printStackTrace();
                LogTrace.info("ws-currency-data","websocket","断开连接或异常");
            }
        }
    }
    public void pairData(Session session, Integer exchangeId, String transactionName) {
        LogTrace.beginTrace("发送消息");
        ApiResultVo resultVo = new ApiResultVo();
        resultVo.setDataStamp(System.currentTimeMillis());
        resultVo.setTradeId(LogTrace.getTrace().getTraceId());
        //String symbol = redisServer.get(RedisKeyApp.APP_WS_K_SESSION_ID+":"+session.getId());

        if (session.isOpen()) {
            LogTrace.infoKvs("ws-pair-data","sessionId" ,session.getId(),"exchangeId",String.valueOf(exchangeId),"transactionName",transactionName);
            try {
                //获取交易对数据
                AppSelfSelectCoinPairVo pairData = kActionDetailService.getPairData(exchangeId,transactionName);
                resultVo.setData(pairData);
                resultVo.setCode(ReturnCode.SUCCESS);
                resultVo.setMessage("成功");
            } catch (Exception e) {
                e.printStackTrace();
                resultVo.setCode(ReturnCode.ERROR);
                resultVo.setMessage("系统异常");
                LogTrace.error("ws-pair-data-error",e);
            }
            try {
                session.getBasicRemote().sendText(JSON.toJSONString(resultVo));
            } catch (IOException e) {
                e.printStackTrace();
                LogTrace.info("ws-pair-data","websocket","断开连接或异常");
            }
        }
    }

    public void pairDataList(Session session, String message) {
        LogTrace.beginTrace("发送消息");
        ApiResultVo resultVo = new ApiResultVo();
        resultVo.setDataStamp(System.currentTimeMillis());
        resultVo.setTradeId(LogTrace.getTrace().getTraceId());
        //String symbol = redisServer.get(RedisKeyApp.APP_WS_K_SESSION_ID+":"+session.getId());

        if (session.isOpen()) {
            LogTrace.infoKvs("ws-pair-data","sessionId" ,session.getId());
            try {
                //获取交易对数据
                List<AppSelfSelectCoinPairVo> pairData = kActionDetailService.getPairDataList(message);
                resultVo.setData(pairData);
                resultVo.setCode(ReturnCode.SUCCESS);
                resultVo.setMessage("成功");
            } catch (Exception e) {
                e.printStackTrace();
                resultVo.setCode(ReturnCode.ERROR);
                resultVo.setMessage("系统异常");
                LogTrace.error("ws-pair-data-error",e);
            }
            try {
                session.getBasicRemote().sendText(JSON.toJSONString(resultVo));
            } catch (IOException e) {
                e.printStackTrace();
                LogTrace.info("ws-pair-data","websocket","断开连接或异常");
            }
        }
    }
}
